/**
 * Created by huj09 on 2017/8/17.
 */

//var loadStage = function () {
var stage = new PIXI.Container(),
	renderer = PIXI.autoDetectRenderer(256, 256, {backgroundColor: 0x1099bb});
renderer.resize(1024, 680);
renderer.view.style.cursor = "cursorStyle";
//renderer.view.style = "margin-top:30px";
document.getElementById('divCanvasContainer').appendChild(renderer.view);

var outlineFilter = new PIXI.filters.OutlineFilter(1, 0x99ff99);
var outlineFilterDisable = new PIXI.filters.OutlineFilter(2, 0xDC143C);
PIXI.loader.add("css/img/bkg.jpg").load(setup);
var resources = PIXI.loader.resources;
var bkgtexture = PIXI.Texture.fromImage('css/img/bkg.jpg');
//var bkgtexture = PIXI.Texture.fromImage('https://tb1.bdstatic.com/tb/cms/frs/bg/default_head20141014.jpg');

var bkg = new PIXI.Sprite(bkgtexture);
bkg.interactive = true;

bkg.on('mousedown', bmousedown)
	.on('mousemove', bmousemove)
	.on('mouseup', bmouseup)
    .on("mouseover", mouseOverOnBkg);

stage.addChild(bkg);

function mouseOverOnBkg(){
}

var graphics = new PIXI.Graphics();
graphics.beginFill(0xFF3300, 0);
graphics.lineStyle(1, 0xffd900, 1);
graphics.nativeLines = true;


//位置参数
var pos = {
	x: 0, y: 0, setValue: function (obj) {
		this.x = obj.x;
		this.y = obj.y
	}
};

//位置和宽高参数
var shape = {
	x: 0, y: 0, width: 0, height: 0, setValue: function (obj) {
		this.x = obj.x;
		this.y = obj.y;
		this.width = obj.width;
		this.height = obj.height;
	}
};

//选中的sprite
var selectedObjct = {multFlag: false, currSel: null, allSel: [], bgdg_x: 0, bgdg_y: 0};

//ctrl键 是否按下
var ctrlPress = false;

function bmousedown(event) {
    this.data = event.data;
    if(chop.chopping){
        chopImg(this.data.getLocalPosition(this.parent));
        graphics.clear();
        chop.chopOver = true;
        return;
    }else if(chop.chopInPic){
        chop.chopInPic = false;
        return;
    }
	this.dragging = true;
	this.data = event.data;
	var position = this.data.getLocalPosition(this.parent);
	pos.setValue(position);
	if (graphics.graphicsData.length > 0) {
		var shapeTp = (graphics.graphicsData[graphics.graphicsData.length - 1]).shape;
		shape.setValue(shapeTp);
	}
	if (false) {
		graphics.clear();
	}
}

function bmousemove(event) {
    if(chop.chopping && !chop.chopOver){
        this.data = event.data;
        drawChopLine(this.data.getLocalPosition(this.parent));
    }
	if (this.dragging) {
		this.data = event.data;
		var position = this.data.getLocalPosition(this.parent);
		graphics.clear();
		// graphics.beginFill(0xffffff,1);//填充
		graphics.lineStyle(1, 0x66ccff, 0.8);

		graphics.drawRect(pos.x, pos.y, position.x - pos.x, position.y - pos.y);
        stage.addChild(graphics);
	}
}

function bmouseup() {
    if(chop.chopping){
        graphics.clear();
        chop.chopping = false;
        chop.chopOver = false;
        return;
    }
	this.dragging = false;
	if (null != selectedObjct.currSel) {
		selectedObjct.currSel.filters = null;
		setDragPoint(selectedObjct.currSel, false);
		selectedObjct.currSel = null;
	}
	if (selectedObjct.allSel.length > 0) {
		selectedObjct.allSel.forEach(function (sprite) {
			setDragPoint(sprite, false);
		});
		selectedObjct.allSel = [];
	}
	if (graphics.graphicsData[0] && graphics.graphicsData[0].shape) {
		recSelect(graphics.graphicsData[0].shape);
	}
	graphics.clear();
}


// 加载 图片
var loadPicture = function () {
	console.log("loadPicture");
	var cpic = PIXI.Texture.fromImage(sessionStorage.imageUrl);
	var img = new PIXI.Sprite(cpic);
	img.interactive = true;
	img.buttonMode = true;
	img.ctrlMode = true;
	img.scale.set(0.5);
	img
		.on('mousedown', onDragStart)
		.on('mouseup', onDragEnd)
		.on('mouseupoutside', onDragEnd)
		.on('mousemove', onDragMove)
		.on('click', onClickSprite)
		.on("mouseover", onMouseOver);

	img.x = 100;
	img.y = 100;
	stage.addChild(img);
	drawDragPoint(img);

};

function onMouseOver(event) {
	//console.log(event);
}

//剪切
var cutPicture = function () {
	if (stage.children.indexOf(shade) == -1) {
		stage.addChild(shade);
	} else {
		stage.removeChild(shade);
	}
};

//剪切透明遮罩
var sdtextture = PIXI.Texture.fromImage('css/img/bkg.jpg');
var shade = new PIXI.Sprite(sdtextture);
shade.type = 'shade';
shade.interactive = true;
shade.alpha = 0;
//shade.width = app.renderer.width;
//shade.height = app.renderer.height;
shade.on('mousedown', shmousedown)
	.on('mousemove', shmousemove)
	.on('mouseup', shmouseup);

function shmousedown(event) {
	this.dragging = true;
	this.data = event.data;
	var position = this.data.getLocalPosition(this.parent);
	pos.setValue(position);
}

function shmousemove(event) {
	if (this.dragging) {
		this.data = event.data;
		var position = this.data.getLocalPosition(this);
		graphics.clear();
		graphics.lineStyle(1, 0x66ccff, 0.8);
		graphics.drawRect(pos.x, pos.y, position.x - pos.x, position.y - pos.y);
		stage.addChild(graphics);
	}
}

function shmouseup() {
	this.dragging = false;
	if (graphics.graphicsData.length == 1) {
		var shapeTp = (graphics.graphicsData[graphics.graphicsData.length - 1]).shape;
		if (shapeTp.width != 0 && shapeTp.height != 0) {

			var bzShape = getStandardShape(shapeTp);
			var cutParam = getCutArea(bzShape, stage.children);
			if (cutParam && cutParam.spt) {
				var scale_x = cutParam.spt.scale.x;
				var scale_y = cutParam.spt.scale.y;
				var texture = cutParam.spt.texture.clone();

				var tx = cutParam.spt.texture.frame.x || 0,
					ty = cutParam.spt.texture.frame.y || 0;
				var rectangle = new PIXI.Rectangle(tx + cutParam.x / scale_x, ty + cutParam.y / scale_y, cutParam.width / scale_x, cutParam.height / scale_y);
				texture.frame = rectangle;
				var cut = new PIXI.Sprite(texture);

				cut.x = 32;
				cut.y = 32;
				cut.scale.set(scale_x, scale_y);
				cut.interactive = true;
				cut.buttonMode = true;
				bindDraggingEvent(cut);
				stage.addChild(cut);
				drawDragPoint(cut);
			}
		}
	}
	graphics.clear();
}


function setup() {

	var left = keyboard(37),
		up = keyboard(38),
		right = keyboard(39),
		down = keyboard(40),
		deleteSprite = keyboard(46),
		ctrl = keyboard(17);

	ctrl.press = function () {
		ctrlPress = true;
	};

	ctrl.release = function () {
		ctrlPress = false;
	};

	deleteSprite.press = function () {
		console.log("press Delete");
	};

	deleteSprite.release = function () {
		console.log("excute Delete");
		if (selectedObjct.currSel) {
			//删除sprite和对应的拖拽点
			removeSprite(selectedObjct.currSel);
			//清空当前选择
			selectedObjct.currSel = null;
		}
		if (selectedObjct.allSel.length > 0) {
			selectedObjct.allSel.forEach(function (sprite) {
				removeSprite(sprite);
			})
			selectedObjct.allSel = [];
		}
	};


	left.press = function () {
		move('x', -5);
	};

	left.release = function () {
		// if (!right.isDown && selectedObjct.currSel.y === 0) {
		//     selectedObjct.currSel.x += 0;
		// }
	};

	up.press = function () {
		move('y', -5);
	};
	up.release = function () {
		// if (!down.isDown && selectedObjct.currSel.x === 0) {
		//     selectedObjct.currSel.y += 0;
		// }
	};


	right.press = function () {
		move('x', 5);
	};
	right.release = function () {
		// if (!left.isDown && selectedObjct.currSel.y === 0) {
		//     selectedObjct.currSel.x += 0;
		// }
	};


	down.press = function () {
		move('y', 5);
	};
	down.release = function () {
		// if (!up.isDown && selectedObjct.currSel.x === 0) {
		//     selectedObjct.currSel.y += 0;
		// }
	};
	renderLoop();
}


function move(axis, distance) {
	if (selectedObjct.currSel) {
		selectedObjct.currSel[axis] += distance;
        selectedObjct.currSel.dragPoint.forEach(function (point) {
            point[axis] += distance;
        })
	}
	if (selectedObjct.allSel.length > 0) {
		selectedObjct.allSel.forEach(function (sprite) {
            sprite[axis] += distance;
            sprite.dragPoint.forEach(function (point) {
                point[axis] += distance;
            })
		})
	}
}


//框选
function recSelect(obj) {
	var cl_x, cl_y, cr_x, cr_y;
	var shape = getStandardShape(obj);
	cl_x = shape.x;
	cl_y = shape.y;
	cr_x = shape.x + shape.width;
	cr_y = shape.y + shape.height;

	var children = stage.children;
	var spt, lu_x, lu_y, rd_x, rd_y;

	if (selectedObjct.currSel) {
		setDragPoint(selectedObjct.currSel, false);
		selectedObjct.currSel.filters = null;
	}
	if (selectedObjct.allSel.length > 0) {
		selectedObjct.allSel.forEach(function (sprite) {
			sprite.filters = null;
			setDragPoint(sprite, false);
		})
		selectedObjct.allSel = [];
	}

	for (var i = 1; i < children.length - 1; i++) {
		spt = children[i];

		lu_x = spt.x - spt.anchor.x * spt.width;
		lu_y = spt.y - spt.anchor.y * spt.height;

		rd_x = spt.x + (1 - spt.anchor.x) * spt.width;
		rd_y = spt.y + (1 - spt.anchor.y) * spt.height;

		if (cl_x < lu_x && cl_y < lu_y && cr_x > rd_x && cr_y > rd_y && spt.type != "dragPoint") {
			if (checkCtrlMode(spt)) {
				spt.filters = [outlineFilterDisable];
			} else {
				spt.filters = [outlineFilter];
			}
			setDragPoint(spt, true);
			//记录sprite的起始位置
			spt.sx = spt.x;
			spt.sy = spt.y;
			selectedObjct.allSel.push(spt);
			selectedObjct.currSel = spt;
		}
	}

	if (selectedObjct.allSel.length > 1) {
		selectedObjct.multFlag = true;
		selectedObjct.currSel = null;
	} else {
		selectedObjct.multFlag = false;
		selectedObjct.allSel = [];
	}
}

//循环舞台
function renderLoop() {
	requestAnimationFrame(renderLoop);
	renderer.render(stage);
}

function onTestClick() {
	renderer.render(stage);
	renderer.view.toBlob(function (blob) {
		var newImg = document.createElement("img"),
			url = URL.createObjectURL(blob);
		newImg.style.marginLeft = "8px";
		newImg.onload = function () {
			// no longer need to read the blob so it's revoked
			URL.revokeObjectURL(url);
		};

		newImg.src = url;
		document.body.appendChild(newImg);
	});
}
//}